//
//  ScrapeUpViewController.m
//  TerritoryShopkeeper
//
//  Created by 李小龙 on 2017/12/28.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "ScrapeUpViewController.h"
#import "ScrapeUpTableViewCell.h"
#import "GoodsDetailViewController.h"
#import "GoodsListModel.h"

@interface ScrapeUpViewController ()<UITableViewDataSource,UITableViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSMutableArray<GoodsListModel *> *tableArray;

@end

@implementation ScrapeUpViewController
#pragma mark - IBAction
- (IBAction)backAction:(id)sender {
    [self disMissSelf];
}
#pragma mark - Get
- (NSMutableArray<GoodsListModel *> *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"凑单商品";
    [self hiddenShadowImage:NO];
    
    self.page = 1;
    [self createTable];
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self getNetData];
}
#pragma mark - Action
static NSString *scrapeUpTableIdentifier = @"scrapeUpTableIdentifier";
- (void)createTable {
    [self.tableView registerNib:[UINib nibWithNibName:@"ScrapeUpTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:scrapeUpTableIdentifier];
    [self.tableView clearExtendCellLine];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self getNetData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getNetData];
    }];
}
- (void)uploadBottom {
    
}
#pragma mark - 网络请求
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetFailure {
    //[(AppDelegate *)[UIApplication sharedApplication].delegate updateBadgeValue:0];
    if (_page != 1) {
        _page--;
    }
}
- (void)getNetSuccess:(NSDictionary *)dics {
    
    if (self.page == 1) {
        [self.tableArray removeAllObjects];
        [self.tableView.mj_footer resetNoMoreData];
    }
    // 数据列表
    NSArray *arr = dics[@"data"];
    if (arr.count == 0 && self.page != 1) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self getNetFailure];
        return;
    }
    for (NSDictionary *dataDic in arr) {
        GoodsListModel *model = [GoodsListModel mj_objectWithKeyValues:dataDic];
        [self.tableArray addObject:model];
    }
    
    if ([dics[@"totalRow"] integerValue] > self.tableArray.count) {
        [self.tableView.mj_footer setHidden:NO];
    } else {
        [self.tableView.mj_footer setHidden:YES];
    }
    
    
    [self.tableView reloadData];
//    if (type == NetWorkTypeFooter) {
//        [self.tableView reloadData];
//    } else {
//        NSMutableIndexSet *sectionSet = [[NSMutableIndexSet alloc] init];
//        for (NSInteger i = 0; i < self.tableArray.count; i++) {
//            [sectionSet addIndex:i];
//        }
//        // 适配iOS11
//        if (@available(iOS 11.0, *)) {
//            [self.tableView performBatchUpdates:^{
//                [self.tableView reloadSections:sectionSet withRowAnimation:UITableViewRowAnimationFade];
//            } completion:^(BOOL finished) {
//
//            }];
//        } else {
//            [self.tableView beginUpdates];
//            [self.tableView reloadSections:sectionSet withRowAnimation:UITableViewRowAnimationFade];
//            [self.tableView endUpdates];
//        }
//    }
}
- (void)getNetData {
    __block typeof(self) blockSelf = self;
    [MYAFNetworking POST:URL_Orders_Together parameters:@{@"gcid":self.gcid,@"pageNumber":@(self.page),@"pageSize":PageSize} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [blockSelf endRefresh];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [blockSelf getNetSuccess:responseObject];
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
            [blockSelf getNetFailure];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
        [blockSelf endRefresh];
        [blockSelf getNetFailure];
    }];
}
- (void)addToShopCart:(GoodsListModel *)model {
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:model.gid forKey:@"gid"];
    //[parameters safeSetObject:model.gaid forKey:@"gaid"];
    [parameters safeSetObject:@"5" forKey:@"gaid"];
    [parameters safeSetObject:@"1" forKey:@"number"];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Add_Shopcart parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            [MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"加入购物车成功~" animated:YES];
            [weakSelf uploadBottom];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - UITableViewDataSoure
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ScrapeUpTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:scrapeUpTableIdentifier forIndexPath:indexPath];
    
    GoodsListModel *model = self.tableArray[indexPath.row];
    // 库存
    //cell.maxCount = [self getStock:model];
    // 商品图片
    [cell.goodImageView sd_setImageWithURL:GetUrl(model.gimg) placeholderImage:PlaceholderImageSmall  changeContentModel:UIViewContentModeScaleAspectFill];
    
    // 商品名
    [cell.goodNameLable setText:model.gname];
    
    NSString *oldStr = [NSString stringWithFormat:@"¥%@",model.goldprice];
    NSString *newStr = [NSString stringWithFormat:@"¥%@",model.gprice];
    if (TextIsNotNil(model.goldprice)) {
        NSString *priceStr = [NSString stringWithFormat:@"%@ %@",newStr,oldStr];
        NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:priceStr];
        [attributeStr addAttributes:@{NSForegroundColorAttributeName:[UIColor ThemeColor],
                                      NSFontAttributeName:TextPingFangFontSize(14)}
                              range:NSMakeRange(0, priceStr.length)];//[priceStr rangeOfString:newStr]
        [attributeStr addAttributes:@{NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle|NSUnderlinePatternSolid),
                                      NSStrokeColorAttributeName:[UIColor gray66Color],
                                      NSFontAttributeName:TextPingFangFontSize(10),
                                      NSForegroundColorAttributeName:[UIColor grayTextColor]}
                              range:NSMakeRange(newStr.length+1, oldStr.length)];//[priceStr rangeOfString:oldStr]
        [cell.goodPriceLabel setAttributedText:attributeStr];
    } else {
        [cell.goodPriceLabel setText:newStr];
    }
    // 加入购物车
    __block typeof(self) blockSelf = self;
    cell.addShopcartBlock = ^{
        [blockSelf addToShopCart:model];
    };
    /*
    // 数量
    [cell.normalCountLabel setText:[NSString stringWithFormat:@"x%@",model.number]];
    // 属性名拼接
    GoodsAttributePriceModel *temp;
    for (GoodsAttributePriceModel *attModel in model.goodsattribute) {
        if ([model.gaid isEqualToString:attModel.gaid]) {
            temp = attModel;
            break;
        }
    }
    NSString *specs = @"";
    if (temp) {
        for (NSInteger i = 0; i < temp.twoattribute.count; i++) {
            TwoAtrributeModel *twoAtt = temp.twoattribute[i];
            if (i == 0) {
                specs = twoAtt.taname;
            } else {
                specs = [NSString stringWithFormat:@"%@;%@",specs,twoAtt.taname];
            }
        }
    }
    [cell.normalSpecsLabel setText:specs];
    
    // 属性名拼接
    [cell.editSpecsLabel setText:specs];
    */
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GoodsListModel *model = self.tableArray[indexPath.row];
    if (!model.isshelves) {
        [MBProgressHUD showError:self.view title:@"该商品已下架" code:@"" animated:YES];
        return;
    }
    GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
    goodsDetailVC.gid = model.gid;
    [self.navigationController pushViewController:goodsDetailVC animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 132;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 132;
}
#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无凑单商品"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    _page = 1;
    [self getNetData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
